/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import io.renren.entity.ColumnEntity;
import io.renren.entity.TableEntity;
import io.renren.service.SysGeneratorService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {
    @Autowired
    private SysGeneratorService sysGeneratorService;

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));

        return R.ok().put("page", pageUtil);
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(String tables, HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(tables.split(","), response);

//		response.reset();
//        response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");
//        response.addHeader("Content-Length", "" + data.length);
//        response.setContentType("application/octet-stream; charset=UTF-8");
//
//        IOUtils.write(data, response.getOutputStream());
    }

    @PostMapping("/viewTables")
    @ResponseBody
    public Object viewTables(MultipartFile file, String t,String sheet) throws Exception {
        String[] tables = t.split(",");
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), sheet);
        List<List<Object>> readAll = reader.read();
        List<TableEntity> tableEntityList = new LinkedList<>();
        TableEntity tableEntity = null;
        List<ColumnEntity> columns = null;
        Map<String, String> map = new HashMap<>();

        for (List<Object> objects : readAll) {

            tb:
            for (int i = 0; i < objects.size(); i++) {

                // 获取表名
                for (String table : tables) {
                    String tableName = String.valueOf(objects.get(i));
                    if (tableName.indexOf(table) > 0 && !map.containsKey(table)) {
                        if (tableEntity != null) {
                            tableEntity.setColumns(columns);
                            tableEntityList.add(tableEntity);
                        }
                        // 初始化表名和列名
                        tableEntity = new TableEntity();
                        columns = new LinkedList<>();
                        tableEntity.setTableName(table);
                        tableEntity.setComments(tableName);
                        // 已经解析的保存到map中
                        map.put(table, tableName);

                        break tb;
                    }
                }

                // 获取主键等
                ColumnEntity c = new ColumnEntity();
                if (objects.get(0) == null) {
                    break;
                }
                c.setComments(objects.get(1).toString());
                c.setColumnName(objects.get(2).toString());

                if (c.getComments().equals(c.getColumnName())) {
                    break;
                }

                c.setDataType(objects.get(3).toString());
                //c.setColumnSize(objects.get(3).toString());
                c.setColumnIsNotNull("NO".equalsIgnoreCase(objects.get(5).toString()) || "FALSE".equalsIgnoreCase(objects.get(5).toString()));
                if (columns != null) {
                    columns.add(c);
                }
                break;
            }
        }
        if (tableEntity != null) {
            tableEntity.setColumns(columns);
            tableEntityList.add(tableEntity);
        }

        List<String> ttt = new LinkedList<>();
        for (TableEntity entity : tableEntityList) {
            String SQL = "CREATE TABLE `" + entity.getTableName() + "` (";
            List<ColumnEntity> columnsGet = entity.getColumns();

            String[] typekey = columnsGet.get(1).getDataType().split(" ");
            SQL += " `" + columnsGet.get(1).getColumnName() + "` " + typekey[0] + /*"(" + columnsGet.get(1).getColumnSize() +*/ " unsigned NOT NULL AUTO_INCREMENT COMMENT '主键id' ,";
            for (int i = 2; i < columnsGet.size(); i++) {

                String[] type = columnsGet.get(i).getDataType().split(" ");

                if (type.length == 1) {
                    SQL += "`" + columnsGet.get(i).getColumnName() + "` " + columnsGet.get(i).getDataType() + " ";
                } else {
                    SQL += "`" + columnsGet.get(i).getColumnName() + "` " + type[0] + " ";
                }

                if (!"datetime".equalsIgnoreCase(columnsGet.get(i).getDataType())) {
                    if ("double".equalsIgnoreCase(columnsGet.get(i).getDataType())) {
                        // SQL += "(" + columnsGet.get(i).getColumnSize() + ") ";
                    } else {
                        if(StringUtils.isNotBlank(columnsGet.get(i).getColumnSize())){
                            SQL += "(" + columnsGet.get(i).getColumnSize() + ") ";

                            // 如果是bigint unsigned
                            if (type.length > 1) {
                                SQL += type[1] + " ";
                            }
                        }
                    }
                }


//                if(!"varchar".equalsIgnoreCase(columnsGet.get(i).getDataType())){
//                    SQL+=  "("+columnsGet.get(i).getColumnSize()+")";
//                }
                if (columnsGet.get(i).getColumnIsNotNull()) {
                    SQL += " NOT NULL ";
                    if ("varchar".equalsIgnoreCase(columnsGet.get(i).getDataType())) {
                        // SQL += " DEFAULT '' ";
                    }
                } else {
                    SQL += " DEFAULT NULL ";
                }
                SQL += " COMMENT '" + columnsGet.get(i).getComments() + "' ,";
            }
            SQL += "  PRIMARY KEY (`" + columnsGet.get(1).getColumnName() + "`)";
            SQL += " ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='" + entity.getComments() + "';";

            ttt.add(SQL);
        }


        //  CREATE TABLE `user` (
        //  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
        //  `username` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
        //  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
        //  `other_code` int(11) DEFAULT NULL,
        //  `source` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
        //  `status` tinyint(1) DEFAULT NULL,
        //  `time_create` datetime DEFAULT NULL,
        //  PRIMARY KEY (`id`)
        //) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='存货档案';

        //  PRIMARY KEY (`inventory_id`),
        //) ENGINE=InnoDB AUTO_INCREMENT=104263 DEFAULT CHARSET=utf8 COMMENT='存货档案';
        StringBuilder tbb = new StringBuilder();
        for (String s : ttt) {
            System.out.println(s);
            tbb.append(s);
        }
        return R.ok().put("tables", tbb.toString());
    }


}
